// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
import * as vscode from 'vscode';
// 界面
import * as fs from 'fs';
import * as path from 'path';
import { MyTreeDataProvider } from './TreeDataProvider';
import { marked } from 'marked';

// This method is called when your extension is activated
// Your extension is activated the very first time the command is executed
export function activate(context: vscode.ExtensionContext) {

    // Use the console to output diagnostic information (console.log) and errors (console.error)
    // This line of code will only be executed once when your extension is activated
    console.log('Congratulations, your extension "foxdo" is now active!');

    // The command has been defined in the package.json file
    // Now provide the implementation of the command with registerCommand
    // The commandId parameter must match the command field in package.json
    // const disposable = vscode.commands.registerCommand('foxdo.helloWorld', () => {
    // 	// The code you place here will be executed every time your command is executed
    // 	// Display a message box to the user
    // 	vscode.window.showInformationMessage('Hello World from foxdo!');
    // });

    // 注册一个命令用于打开Webview面板
    let disposable = vscode.commands.registerCommand('extension.openWebviewPanel', () => {
        // 获取当前活动的文本编辑器
        const activeEditor = vscode.window.activeTextEditor;
        if (activeEditor) {
            console.log(`Current active editor file: ${activeEditor.document.fileName}`);
        } else {
            console.log('No active editor found.');
        }

        // 创建并显示一个新的Webview面板
        const panel = vscode.window.createWebviewPanel(
            'foxdoPanel', // 面板的标识符
            'Foxdo Panel', // 面板的标题
            vscode.ViewColumn.One, // 显示在编辑器的哪个区域
            {
                enableScripts: true, // 启用脚本
                retainContextWhenHidden: true, // 当面板隐藏时保持内容状态
                localResourceRoots: [
                    vscode.Uri.file(context.extensionPath) // 允许访问扩展的资源
                ]
            } // 面板的选项
        );

        // 设置Webview的HTML内容
        panel.webview.html = getWebviewContent(context.extensionPath);
        vscode.window.showInformationMessage('Hello World from foxdo!');
    });

    // 新增命令用于打开指定文本文档
    let openDocumentDisposable = vscode.commands.registerCommand('extension.openDocument', async () => {
        // 显示输入框让用户输入文件路径
        const documentPath = await vscode.window.showInputBox({
            prompt: 'Enter the path to the document you want to open',
            placeHolder: 'e.g. /path/to/document.txt'
        });

        if (documentPath) {
            // 尝试打开指定路径的文档
            const uri = vscode.Uri.file(documentPath);
            try {
                const document = await vscode.workspace.openTextDocument(uri);
                await vscode.window.showTextDocument(document);
                console.log(`Opened document: ${document.fileName}`);
            } catch (error) {
                vscode.window.showErrorMessage(`Failed to open document: ${error}`);
                console.error(`Failed to open document: ${error}`);
            }
        } else {
            vscode.window.showInformationMessage('No document path provided.');
        }
    });

    // 新增命令用于打开外链
    let openExternalLinkDisposable = vscode.commands.registerCommand('extension.openExternalLink', async () => {
        // 显示输入框让用户输入URL
        const url = await vscode.window.showInputBox({
            prompt: 'Enter the URL you want to open',
            placeHolder: 'e.g. https://example.com'
        });

        if (url) {
            // 尝试打开指定的URL
            const uri = vscode.Uri.parse(url);
            try {
                await vscode.env.openExternal(uri);
                console.log(`Opened external link: ${url}`);
            } catch (error) {
                vscode.window.showErrorMessage(`Failed to open external link: ${error}`);
                console.error(`Failed to open external link: ${error}`);
            }
        } else {
            vscode.window.showInformationMessage('No URL provided.');
        }
    });

    // 新增命令用于打开终端并执行命令
    let openTerminalAndExecuteCommandDisposable = vscode.commands.registerCommand('extension.openTerminalAndExecuteCommand', async () => {
        // 默认命令为 'ls'
        const defaultCommand = 'ls';
        
        // 显示输入框让用户输入命令，如果用户没有输入则使用默认命令
        const command = await vscode.window.showInputBox({
            prompt: 'Enter the command you want to execute in the terminal',
            placeHolder: 'e.g. echo Hello, World!',
            value: defaultCommand // 设置默认值为 'ls'
        });

        if (command) {
            // 创建一个新的终端
            const terminal = vscode.window.createTerminal('Foxdo Terminal');
            // 在终端中执行命令
            terminal.sendText(command);
            // 显示终端
            terminal.show();
            console.log(`Executed command in terminal: ${command}`);
        } else {
            vscode.window.showInformationMessage('No command provided.');
        }
    });

    // 新增命令用于打开终端并执行命令
    let openTerminalDisposable = vscode.commands.registerCommand('extension.openTerminal', async () => {
        // 默认命令为 'cd D:\\workspace ; ls'
        const defaultCommand = 'cd D:\\workspace ; ls';
        
        // 执行默认命令
        const command = defaultCommand;

        if (command) {
            // 创建一个新的终端
            const terminal = vscode.window.createTerminal('Foxdo Terminal');
            // 在终端中执行命令
            terminal.sendText(command);
            // 显示终端
            terminal.show();
            console.log(`Executed command in terminal: ${command}`);
        } else {
            vscode.window.showInformationMessage('No command provided.');
        }
    });
    console.log('注册侧边栏 Webview 视图提供者!');
    // 注册侧边栏 Webview 视图提供者
    const webviewViewProvider = vscode.window.registerWebviewViewProvider('foxdoSidebarView', {
        resolveWebviewView: (webviewView) => {
            webviewView.webview.options = {
                enableScripts: true,
                localResourceRoots: [vscode.Uri.file(path.join(context.extensionPath, 'media'))]
            };

            webviewView.webview.html = getSiderWebviewContent(context.extensionPath);
            console.log('Webview view created');

            webviewView.onDidDispose(() => console.log('Webview view disposed'), null, context.subscriptions);
        }
    });
    let openWebPageDisposable = vscode.commands.registerCommand('extension.openWeb', () => {
        const panel = vscode.window.createWebviewPanel(
            'webPage', // viewType
            'Web Page', // Title
            vscode.ViewColumn.One, // Editor column to show the new webview panel in.
            {} // Webview options. More on these later.
        );

        // And set its HTML content
        panel.webview.html = getSubappWebviewContent('https://www.example.com');
    });
    // 新增命令用于打开终端并执行命令
    let openSubappDisposable = vscode.commands.registerCommand('extension.openSubapp', async () => {
        const panel = vscode.window.createWebviewPanel(
            'webPage', // viewType
            'Web Page', // Title
            vscode.ViewColumn.One, // Editor column to show the new webview panel in.
            {} // Webview options. More on these later.
        );

        // And set its HTML content
        panel.webview.html = getSubappWebviewContent('https://www.example.com');
    });

    let markdownEditorDisposable = vscode.commands.registerCommand('extension.openMarkdownEditor', async () => {
        // 创建并显示Markdown编辑器面板
        const panel = vscode.window.createWebviewPanel(
            'markdownEditor',
            'Markdown Editor',
            vscode.ViewColumn.One,
            {
                enableScripts: true,
                retainContextWhenHidden: true,
                localResourceRoots: [
                    vscode.Uri.file(path.join(context.extensionPath, 'media')),
                    vscode.Uri.file(path.join(context.extensionPath, 'node_modules'))
                ]
            }
        );
        
        // 设置Webview内容
        panel.webview.html = getMarkdownEditorContent(context, panel);
        
        // 修改消息处理逻辑
        panel.webview.onDidReceiveMessage(
            message => {
                switch (message.type) {
                    case 'updatePreview':
                        updatePreview(panel, message.content);
                        break;
                    // 新增提示处理
                    case 'showAlert':
                        console.log(`Received alert: ${message.content}`);
                        vscode.window.showInformationMessage(message.content);
                        break;
                }
            },
            undefined,
            context.subscriptions
        );
    });
    
    
    context.subscriptions.push(markdownEditorDisposable);
    context.subscriptions.push(openWebPageDisposable);
    context.subscriptions.push(openSubappDisposable);

    context.subscriptions.push(webviewViewProvider);

    context.subscriptions.push(disposable);
    context.subscriptions.push(openDocumentDisposable);
    context.subscriptions.push(openExternalLinkDisposable);
    context.subscriptions.push(openTerminalAndExecuteCommandDisposable);
    context.subscriptions.push(openTerminalDisposable);
 
    const treeDataProvider = new MyTreeDataProvider();
    vscode.window.registerTreeDataProvider('foxdoSidebarTree', treeDataProvider);

    let disposableTree = vscode.commands.registerCommand('extension.refreshEntry', () => treeDataProvider.refresh());
    context.subscriptions.push(disposableTree);

    // 创建状态栏图标
    const statusBarItem = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Right, 100);
    statusBarItem.text = "$(gear)"; // 使用齿轮图标
    statusBarItem.tooltip = "Foxdo 配置"; // 设置工具提示
    statusBarItem.command = "extension.showFoxConfiguration"; // 设置点击图标时执行的命令
    statusBarItem.show(); // 显示状态栏图标

    // 注册命令以显示配置项
    let showConfigurationDisposable = vscode.commands.registerCommand('extension.showFoxConfiguration', () => {
        // 显示快速选择菜单
        vscode.window.showQuickPick(['配置项1', '配置项2', '配置项3'], {
            placeHolder: '选择一个配置项'
        }).then(selection => {
            if (selection) {
                vscode.window.showInformationMessage(`你选择了: ${selection}`);
            }
        });
    });

    // 将状态栏和命令的 disposable 添加到 subscriptions 中
    context.subscriptions.push(statusBarItem);
    context.subscriptions.push(showConfigurationDisposable);

}

function getSiderWebviewContent(extensionPath: string): string {
    const sidebarHtmlPath = path.join(extensionPath, 'media', 'sidebar.html');
    try {
        const htmlContent = fs.readFileSync(sidebarHtmlPath, 'utf8');
        console.log('Sidebar HTML loaded successfully:', sidebarHtmlPath);
        return htmlContent;
    } catch (error) {
        console.error('Failed to load sidebar HTML:', error);
        return '<html><body><h1>Failed to load sidebar</h1></body></html>';
    }
}

function getWebviewContent(extensionPath: string) {
    const htmlPath = path.join(extensionPath, 'src', 'webview.html');
    return fs.readFileSync(htmlPath, 'utf-8');
}
function getSubappWebviewContent(url: string) {
    return `
        <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>Web Page</title>
        </head>
        <body>
            <iframe src="${url}" width="100%" height="100%" frameborder="0"></iframe>
        </body>
        </html>
    `;
}


function getMarkdownEditorContent(context: vscode.ExtensionContext, panel: vscode.WebviewPanel): string {
    // 添加错误处理
    try {
        const htmlPath = path.join(context.extensionPath, 'media', 'markdown-editor.html');
        let htmlContent = fs.readFileSync(htmlPath, 'utf8');

        // 转换所有本地资源路径
        const resources = {
            css: panel.webview.asWebviewUri(
                vscode.Uri.file(path.join(context.extensionPath, 'media', 'editor.css'))
            ),
            markedJs: panel.webview.asWebviewUri(
                vscode.Uri.file(path.join(context.extensionPath, 'node_modules', 'marked', 'marked.min.js'))
            )
        };

        // 使用更可靠的占位符替换方式
        return htmlContent
            .replace(/<!--\s*CSS_PLACEHOLDER\s*-->/g, `<link rel="stylesheet" href="${resources.css}">`)
            .replace(/<!--\s*MARKED_JS_PLACEHOLDER\s*-->/g, `<script src="${resources.markedJs}"></script>`);
            
    } catch (error) {
        console.error(`Failed to load markdown editor: ${error}`);
        return `<html><body><h1>Error loading editor</h1><p>${error}</p></body></html>`;
    }
}


function updatePreview(panel: vscode.WebviewPanel, content: string) {
    panel.webview.postMessage({
        type: 'updatePreview',
        html: marked.parse(content)
    });
}


// This method is called when your extension is deactivated
export function deactivate() {}